package Syntax_Anlayzer;

import java.util.*;

public class ForecastAnalysis {
    private String content;
    private int tokenIndex;
    private String startSymbol; // 起始符号

    // 假设content是单个字符串，我们将逐个字符地处理它
    public ForecastAnalysis(String content, String startSymbol) {
        this.content = content;
        this.tokenIndex = 0;
        this.startSymbol = startSymbol;
    }

    public void forecastAnalysis() {
        Stack<String> stack = new Stack<>();
        stack.push("$");
        stack.push(startSymbol);

        System.out.println("Starting analysis:");
        System.out.println("[1]\t[" + stack.peek() + "#" + (tokenIndex < content.length() ? content.charAt(tokenIndex) : "EOF") + "]\t[move]");

        int ruleNumber = 1; // 规则序号，用于输出
        while (!stack.isEmpty()) {
            String top = stack.peek();
            String inputSymbol = tokenIndex < content.length() ? String.valueOf(content.charAt(tokenIndex)) : "$";

            if (top.equals("$") && inputSymbol.equals("$")) {
                System.out.println("[" + ruleNumber++ + "]\t[" + top + "#" + inputSymbol + "]\t[accept]");
                break;
            } else if (Init.V_T.contains(top) || top.equals("$")) {
                if (top.equals(inputSymbol)) {
                    System.out.println("[" + ruleNumber++ + "]\t[" + top + "#" + inputSymbol + "]\t[move]");
                    stack.pop();
                    tokenIndex++;
                } else {
                    System.out.println("[" + ruleNumber++ + "]\t[" + top + "#" + inputSymbol + "]\t[error]");
                    break;
                }
            } else {
                if (ForecastAnalysisTable.forecastAnalysisTable.containsKey(top) && ForecastAnalysisTable.forecastAnalysisTable.get(top).containsKey(inputSymbol)) {
                    List<String> production = ForecastAnalysisTable.forecastAnalysisTable.get(top).get(inputSymbol);
                    System.out.println("[" + ruleNumber++ + "]\t[" + top + "#" + inputSymbol + "]\t[reduction by rule " + production + "]");
                    stack.pop();
                    for (String symbol : production) {
                        if (!symbol.equals("$")) {
                            stack.push(symbol);
                        }
                    }
                } else {
                    System.out.println("[" + ruleNumber++ + "]\t[" + top + "#" + inputSymbol + "]\t[error]");
                    break;
                }
            }
        }

        if (tokenIndex == content.length() && stack.peek().equals("$")) {
            System.out.println("Analysis complete: Accept");
        } else {
            System.out.println("Analysis failed: Reject");
        }
    }

    // Getter and setter methods for content
    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }
}